<?php
namespace Home\Model;
use Think\Model;

class CategoryModel extends Model
{

    public function getAll()
    { //获得所有栏目
        return $this->order('cat_order asc')->select();
    }

    //获得栏目的家谱树
    public function getFamily($id=0) {
        $tree = array();
        while($id>0) {
            foreach($this->getAll() as $k=>$v) {
                if($v['cat_id'] == $id) {
                    $tree[$k]['cat_name'] = $v['cat_name'];
                    $tree[$k]['cat_id'] = $v['cat_id'];
                    $id = $v['parent_id'];
                    break;
                }
            }

        }

        return array_reverse($tree);
    }

    //获取子孙栏目id
    public function getSonId($id=0,$lev=0)
    {
        $tree = array();
        //if($lev==0)$tree = array($id);
        foreach ($this->getAll() as $k=>$v) {
            if ($v['parent_id'] == $id) {

                $tree[] = $v['cat_id'];
                $tree = array_merge($tree, $this->getSonId($v['cat_id'],$lev+1));
            }
        }
        return $tree;
    }
    /*
   getCatTree
   pram: int $id
   return $id栏目的子孙树
   */
    public function getCatTree($id=0, $lev=0) {
            $tree = array();
            foreach ($this->getAll() as $k=>$v) {
                if ($v['parent_id'] == $id) {
                    $v['lev'] = $lev;
                    $v['count'] =  M('Article')->where(array('cat_id'=>$v['cat_id']))->count();
                    $tree[] = $v;
                    $tree = array_merge($tree, $this->getCatTree($v['cat_id'], $lev + 1));
                }
            }
            return $tree;
        }




}
